const { sqlOne, sqlBatch } = require('./src/db/common')
const RedisClient = require('./src/utils/redis-client');
const systeminformation = require('systeminformation');

// 递增 Redis 中的访问量  
async function incrementAndGetViews(articleId) {
    return new Promise((resolve, reject) => {
        RedisClient.client.incr(`article:${articleId}:views`, (err, views) => {
            if (err) {
                reject(err);
            } else {
                resolve(views);
            }
        });
    });
}

function getAllArticleId() {
    return new Promise((res, rel) => {
        // 获取所有文章 ID  
        RedisClient.client.smembers('articles:ids', (err, articleIds) => {
            if (err) {
                console.error('Error fetching article IDs:', err);
                rel(err)
            } else {
                console.log('Article IDs:', articleIds);
                // 现在你可以遍历 articleIds 来处理每个文章  
                res(articleIds)
            }
        });
    })
}

// 更新数据库中的访问量  
async function updateViewsInDb(sql, value) {
    try {
        const [result] = await sqlBatch(sql, value);
        if (result.affectedRows > 0) {
            console.log(`Updated views for article ${value}`);
        }
    } catch (error) {
        console.error(`Error updating views for article ${value}:`, error);
    }
}



// 定时检查 CPU 使用率并更新访问量  
async function checkAndUpdateViews() {
    try {
        const data = await systeminformation.currentLoad();
        console.log(data.currentLoad)
        const cpuUsage = data.currentLoad;

        if (cpuUsage < 10) { // 如果 CPU 占用小于 10%  
            // 假设我们想要更新所有文章的访问量（这里只是示例，您可能只需要更新特定的文章）  


            const articleIds = await getAllArticleId(); // 示例文章 ID 列表  


            let sql = '';

            const value = []
            for (const articleId of articleIds) {
                try {
                    const views = await incrementAndGetViews(articleId);
                    sql += 'UPDATE t_article SET view_count = view_count + ? WHERE id = ?;';
                    value.push(Number(views))
                    value.push(Number(articleId))
                } catch (error) {
                    console.error(`Error getting or updating views for article ${articleId}:`, error);
                }

            }
            await updateViewsInDb(sql, value);
            for (const articleId of articleIds) {
                // 使用示例  
                resetViews(articleId)
                    .then(() => console.log(articleId + '--Views reset to 0'))
                    .catch(err => console.error('Error resetting views:', err));
            }
        } else {
            console.log('CPU usage is too high, skipping sync.');
        }
    } catch (error) {
        console.error('Error getting system information:', error);
    }
}

// 重置 Redis 中的访问量到 0  
async function resetViews(articleId) {
    return new Promise((resolve, reject) => {
        RedisClient.client.set(`article:${articleId}:views`, 0, (err) => {
            if (err) {
                reject(err);
            } else {
                resolve();
            }
        });
    });
}


// 设置定时器，每 5 分钟执行一次 checkAndUpdateViews 函数  
setInterval(checkAndUpdateViews, 5 * 30 * 1000); // 5 minutes in milliseconds  * 60